package com.haipi.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.common.dao.impl.DaoUtils;
import com.haipi.dao.IMailDAO;
import com.haipi.model.MailInfo;

@Component("mailDAO")
@Scope("singleton")
public class MailDAOImpl extends DaoUtils implements IMailDAO
{

	@Override
	public List<MailInfo> getSendMaiList()
	{
		Date nowDate = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String nowDateTime = dateFormat.format(nowDate);
		String sql = "select * from t_mail where send_time <= :nowDateTime and send_state = '0'";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("nowDateTime", nowDateTime);
	
		return toMailInfoList(baseJdbcDao.selectForParam(sql, paramMap));
	}
	
	public int deleteMail(List<MailInfo> list)
	{
	    StringBuffer sql = new StringBuffer();
	    Map<String, Object> params = new HashMap<String, Object>();
        sql.append("update t_mail set send_state = '1' where id in(");
        for (int i = 0; i < list.size(); i++)
        {
            sql.append(":id"+i);
            params.put("id"+i, list.get(i).getId());
            if (i == list.size()-1)
            {
                sql.append(")");
            }
            else
            {
                sql.append(",");
            }
        }
        return baseJdbcDao.deleteForParam(sql.toString(), params);
	}
	
	public int deleteMail(Integer commId)
    {
        Map<String, Object> params = new HashMap<String, Object>();
        String sql = "update t_mail set send_state = '1' where comm_id = :comm_id";
        params.put("comm_id", commId);
        return baseJdbcDao.deleteForParam(sql, params);
    }
	
	public List<MailInfo> toMailInfoList(List<Map<String, Object>> mailInfoMaps)
	{
		List<MailInfo> mailInfos = new ArrayList<MailInfo>();

		for (int i = 0; i < mailInfoMaps.size(); i++)
		{
			MailInfo mailInfo = new MailInfo();
			mailInfo.setAddressee((String)mailInfoMaps.get(i).get("addressee"));
			mailInfo.setId((Integer)mailInfoMaps.get(i).get("id"));
			mailInfo.setRemindType((String)mailInfoMaps.get(i).get("remind_type"));
			mailInfo.setCommId((Integer)mailInfoMaps.get(i).get("comm_id"));
			mailInfo.setSendState((String)mailInfoMaps.get(i).get("send_state"));
			mailInfo.setSendTime((String)mailInfoMaps.get(i).get("send_time"));
			mailInfos.add(mailInfo);

		}

		return mailInfos;
	}

    
}
